package com.xingzhi.shortvideosharingplatform.controller;

import com.xingzhi.shortvideosharingplatform.common.Result;
import com.xingzhi.shortvideosharingplatform.dto.FollowingUserDTO;
import com.xingzhi.shortvideosharingplatform.dto.UserFollowDTO;
import com.xingzhi.shortvideosharingplatform.service.UserFollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/follows")
public class UserFollowController {

    @Autowired
    private UserFollowService userFollowService;
    
    /**
     * 检查是否已关注
     * @param followerId 关注者ID
     * @param followingId 被关注者ID
     * @return 是否已关注
     */
    @GetMapping("/check")
    public Result<Boolean> checkFollow(@RequestParam Long followerId, @RequestParam Long followingId) {
        if (followerId == null || followingId == null) {
            return Result.error(400,"参数不能为空");
        }
        
        boolean isFollowed = userFollowService.isFollowed(followerId, followingId);
        return Result.success(isFollowed);
    }
    
    /**
     * 关注用户
     * @param followDTO 关注信息
     * @return 结果
     */
    @PostMapping
    public Result<Boolean> follow(@RequestBody UserFollowDTO followDTO) {
        if (followDTO == null || followDTO.getFollowerId() == null || 
            followDTO.getFollowingId() == null) {
            return Result.error(400,"参数不完整");
        }
        
        boolean success = userFollowService.follow(followDTO);
        if (success) {
            return Result.success(true, "关注成功");
        } else {
            return Result.error(400,"关注失败");
        }
    }
    
    /**
     * 取消关注
     * @param followerId 关注者ID
     * @param followingId 被关注者ID
     * @return 结果
     */
    @DeleteMapping
    public Result<Boolean> unfollow(@RequestParam Long followerId, @RequestParam Long followingId) {
        if (followerId == null || followingId == null) {
            return Result.error(400,"参数不能为空");
        }
        
        boolean success = userFollowService.unfollow(followerId, followingId);
        if (success) {
            return Result.success(true, "取消关注成功");
        } else {
            return Result.error(400,"取消关注失败");
        }
    }
    
    /**
     * 获取用户关注的人列表
     * @param userId 用户ID
     * @return 关注的用户列表
     */
    @GetMapping("/following/{userId}")
    public Result<List<FollowingUserDTO>> getFollowingList(@PathVariable Long userId) {
        if (userId == null || userId <= 0) {
            return Result.error(400, "用户ID不合法");
        }
        
        try {
            List<FollowingUserDTO> followingList = userFollowService.getFollowingList(userId);
            return Result.success(followingList);
        } catch (Exception e) {
            log.error("获取用户关注列表失败", e);
            return Result.error(500, "获取关注列表失败: " + e.getMessage());
        }
    }
} 